﻿using System;
using System.Linq;
using System.Web;
using System.Web.Security;
using PD.DataAccess;

namespace PD.DataAccess
{
    /// <summary>
    /// Various utilities and extensions methods for HTTP context object.
    /// </summary>
    public static class HttpContextHelper
    {
        /// <summary>
        /// Gets the provider user key of the current user.
        /// </summary>
        /// <param name="context">The current HTTP context.</param>
        /// <returns>
        /// The provider user key of the current user.
        /// </returns>
        public static Guid? ProviderUserKey(this HttpContext context)
        {
            MembershipUser user = Membership.GetUser(context.User.Identity.Name);
            if (user != null)
            {
                return (Guid)user.ProviderUserKey;
            }

            return null;
        }

        /// <summary>
        /// Gets the current configuration.
        /// </summary>
        /// <param name="context">The current HTTP context.</param>
        /// <returns>
        /// The current configuration.
        /// </returns>
        public static Config Configuration(this HttpContext context)
        {
            Guid applicationId = context.ApplicationId();
            using (PDDataClassesDataContext dataContext = new PDDataClassesDataContext())
            {
                return dataContext.Configs.FirstOrDefault(x => x.ApplicationId == applicationId);
            }

            throw new InvalidOperationException();
        }

        /// <summary>
        /// Get the identifier of the current application.
        /// </summary>
        /// <param name="context">The current HTTP context.</param>
        /// <returns>
        /// The identifier of the current application.
        /// </returns>
        internal static Guid ApplicationId(this HttpContext context)
        {
            Guid? providerUserKey = context.ProviderUserKey();
            if (providerUserKey.HasValue)
            {
                using (PDDataClassesDataContext dataContext = new PDDataClassesDataContext())
                {
                    aspnet_User user = dataContext.aspnet_Users.FirstOrDefault(x => x.UserId == providerUserKey.Value);
                    if (user != null)
                    {
                        return user.ApplicationId;
                    }
                }
            }

            throw new InvalidOperationException();
        }
    }
}